package com.twu.biblioteca.Actions;
import com.twu.biblioteca.Interfaces.MenuItems;
import com.twu.biblioteca.Models.User;
import com.twu.biblioteca.Models.UserList;

import java.io.IOException;

public class UserLogin implements MenuItems
{
    public Boolean isLoggedIn = false;
    UserList userList;

    public UserLogin(UserList list)
    {
        userList = list;
    }

    @Override
    public void takeAction() throws IOException
    {
        System.out.println("Enter Username:");
        InputReader inputReader = new InputReader();
        String userName = inputReader.readUserInput();
        int countAttempts = 0;
        while(!isLoggedIn)
        {
            if(countAttempts == 5)break;
            //validate the user string format
            Boolean isValidUserName = userName.matches("[0-9]{3}-[0-9]{4}");
            if(!isValidUserName)
            {
                countAttempts++;
                System.out.println("Invalid user name!");
                break;
            }
            else
            {
                User user = userList.getUser(userName);
                if(user!= null)
                {
                    System.out.println("Enter password");
                    inputReader = new InputReader();
                    String password = inputReader.readUserInput();

                    if(userList.validatePassword(user.userName,password))
                    {
                        System.out.println("You are now logged in");
                        userList.logOutAll();
                        user.setLoggedIn(true);
                        isLoggedIn = true;
                    }
                    else
                    {
                        System.out.println("Enter credentials again!");
                    }
                }
                else
                    System.out.println("Invalid user!");
            }
        }
    }
}
